package com.zykj.thread.concurrent.exchanger;

import java.util.Random;
import java.util.concurrent.Exchanger;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhoulj(周利军) [1217102780@qq.com]
 * @Module ID:   <(模块)类编号，可以引用系统设计中的类编号>
 * @Comments: <对此类的描述，可以引用系统设计中的描述>
 * @JDK version used:      <JDK1.8> 40
 * @since 2019/1/15-17:40
 */
public class ExchangeDemo {


    public static void main(String[] args) {
        // 实现两个线程之间的数据交换
        Exchanger<String> exchanger = new Exchanger<String>();
        ExecutorService executorService = Executors.newCachedThreadPool();


        executorService.execute((Runnable)()->{
            String data = "JAVA";
            int ran =new Random().nextInt(10000);
            try {
                Thread.sleep(ran);
                System.out.println(Thread.currentThread().getName()+"线程执行完成， 等待数据交换， data:"+data);
                data = exchanger.exchange(data);
                System.out.println(Thread.currentThread().getName()+"线程数据交换完成，data:"+data);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        executorService.execute((Runnable)()->{
            String data = "C++";
            int ran =new Random().nextInt(10000);
            try {
                Thread.sleep(ran);
                System.out.println(Thread.currentThread().getName()+"线程执行完成， 等待数据交换， data:"+data);
                data = exchanger.exchange(data);
                System.out.println(Thread.currentThread().getName()+"线程数据交换完成，data:"+data);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });


    }
}
